package com.commerce.user.controller;

import com.commerce.common.entity.Favorite;
import com.commerce.common.utils.PageResult;
import com.commerce.common.utils.Result;
import com.commerce.user.service.FavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收藏夹控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/favorites")
@CrossOrigin
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;

    /**
     * 添加收藏
     */
    @PostMapping
    public Result<Boolean> addFavorite(@RequestBody Favorite favorite) {
        try {
            boolean success = favoriteService.addFavorite(favorite.getUserId(), favorite.getProductId());
            return Result.success(success);
        } catch (Exception e) {
            log.error("添加收藏失败", e);
            return Result.error("添加收藏失败：" + e.getMessage());
        }
    }

    /**
     * 删除收藏
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> removeFavorite(@PathVariable Long id) {
        try {
            boolean success = favoriteService.removeById(id);
            return Result.success(success);
        } catch (Exception e) {
            log.error("删除收藏失败", e);
            return Result.error("删除收藏失败：" + e.getMessage());
        }
    }

    /**
     * 根据商品ID删除收藏
     */
    @DeleteMapping("/product/{productId}")
    public Result<Boolean> removeFavoriteByProductId(@PathVariable Long productId) {
        try {
            // 从请求头或参数中获取用户ID，这里简化处理，实际应该从JWT token中获取
            // 暂时通过查询参数获取用户ID
            boolean success = favoriteService.removeFavoriteByProductId(productId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("删除收藏失败", e);
            return Result.error("删除收藏失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除收藏
     */
    @DeleteMapping("/batch")
    public Result<Boolean> batchRemoveFavorites(@RequestBody List<Long> ids) {
        try {
            boolean success = favoriteService.removeByIds(ids);
            return Result.success(success);
        } catch (Exception e) {
            log.error("批量删除收藏失败", e);
            return Result.error("批量删除收藏失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户收藏列表
     */
    @GetMapping("/user/{userId}")
    public Result<Map<String, Object>> getUserFavorites(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size) {
        try {
            PageResult<Map<String, Object>> pageResult = favoriteService.getUserFavorites(userId, page, size);

            // 构造前端期望的数据结构
            Map<String, Object> result = new HashMap<>();
            result.put("content", pageResult.getContent());
            result.put("totalElements", pageResult.getTotalElements());
            result.put("totalPages", (pageResult.getTotalElements() + size - 1) / size);
            result.put("currentPage", page);
            result.put("size", size);

            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户收藏列表失败", e);
            return Result.error("获取用户收藏列表失败：" + e.getMessage());
        }
    }

    /**
     * 检查商品是否已收藏
     */
    @GetMapping("/check")
    public Result<Boolean> checkFavorite(
            @RequestParam Long userId,
            @RequestParam Long productId) {
        try {
            boolean isFavorite = favoriteService.checkFavorite(userId, productId);
            return Result.success(isFavorite);
        } catch (Exception e) {
            log.error("检查收藏状态失败", e);
            return Result.error("检查收藏状态失败：" + e.getMessage());
        }
    }

    /**
     * 切换收藏状态
     */
    @PostMapping("/toggle")
    public Result<Boolean> toggleFavorite(@RequestBody Favorite favorite) {
        try {
            boolean isFavorite = favoriteService.toggleFavorite(favorite.getUserId(), favorite.getProductId());
            return Result.success(isFavorite);
        } catch (Exception e) {
            log.error("切换收藏状态失败", e);
            return Result.error("切换收藏状态失败：" + e.getMessage());
        }
    }
}
